// Copyright (C) 2020-2022 Intel Corporation
//
// SPDX-License-Identifier: MIT

import React, { useEffect } from 'react';
import Icon from '@ant-design/icons';

import { PolylineIcon } from 'icons';
import { ShapeType } from 'reducers';
import { Canvas } from 'cvat-canvas-wrapper';

import { useControlsDraw } from './useControlsDraw';

export interface Props {
    canvasInstance: Canvas;
    isDrawing: boolean;
    disabled?: boolean;
}

function DrawPolylineControl(props: Props): JSX.Element {
    const { canvasInstance, isDrawing, disabled } = props;

    const { onDraw } = useControlsDraw();

    const dynamicIconProps = isDrawing
        ? {
              className: 'cvat-draw-polyline-control cvat-active-canvas-control',
              onClick: (): void => {
                  canvasInstance.draw({ enabled: false });
              },
          }
        : {
              className: 'cvat-draw-polyline-control',
              onClick: () => {
                  onDraw(ShapeType.POLYLINE);
              },
          };

    function handleCanvasDrawn(e: any) {
        if (e.detail.state?.shapeType !== ShapeType.POLYLINE) {
            return;
        }
        setTimeout(() => {
            onDraw(ShapeType.POLYLINE);
        }, 0);
    }

    useEffect(() => {
        canvasInstance.html().addEventListener('canvas.drawn', handleCanvasDrawn);
        return () => {
            canvasInstance.html().removeEventListener('canvas.drawn', handleCanvasDrawn);
        };
    }, []);

    return disabled ? (
        <Icon className='cvat-draw-polyline-control cvat-disabled-canvas-control' component={PolylineIcon} />
    ) : (
        <Icon {...dynamicIconProps} component={PolylineIcon} />
    );
}

export default React.memo(DrawPolylineControl);
